/**
 * probject:cim-core
 * @version 1.5.0
 * 
 * @author 3979434@qq.com
 */  
package manager;

import java.util.Collection;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.mina.core.session.IoSession;

import im.notify.server.UserInfoAttached;


/** 
 * 自带默认 session管理实现， 各位可以自行实现 AbstractSessionManager接口来实现自己的 session管理
 *服务器集群时 须要将CIMSession 信息存入数据库或者nosql 等 第三方存储空间中，便于所有服务器都可以访问
 */
public class DefaultSessionManager implements SessionManager{


    private static ConcurrentHashMap<String,IoSession> sessions =new  ConcurrentHashMap<String,IoSession>();
    
    
    private static final AtomicInteger connectionsCounter = new AtomicInteger(0);
 
    
    private static DefaultSessionManager s = new DefaultSessionManager();
    
    public static DefaultSessionManager share()
    {
    	return s;
    }

    /**
     *  
     */
    public void addSession(String account,IoSession session) {
        if(session!=null)
        {
        	sessions.put(account, session);
        	connectionsCounter.incrementAndGet();
        }
        
    }

     
    public IoSession getSession(String account) {
       return sessions.get(account);
    }

    

     
    public Collection<IoSession> getSessions() {
        return sessions.values();
    }
 
    public void  removeSession(IoSession session) {
        UserInfoAttached info = (UserInfoAttached) session.getAttribute("userInfo");
        sessions.remove(info.getUserAccount());
    }

     
    public void  removeSession(String account) {
    	sessions.remove(account);
    }
    
    
    public boolean containsCIMSession(String account)
    {
    	return sessions.containsKey(account);
    }

    
    public String getAccount(IoSession ios)
    {
    	UserInfoAttached info = (UserInfoAttached) ios.getAttribute("userInfo");
    	return info.getUserAccount();
    }


	@Override
	public void updateSession(IoSession session) {
		UserInfoAttached info = (UserInfoAttached) session.getAttribute("userInfo");
		sessions.put(info.getUserAccount(), session);
	}


	@Override
	public void setInvalid(String account) {
		
	}
	
	public boolean isSessionOnLine(String account)
	{
		return sessions.get(account) != null ? true:false;
	}
 
}
